// 引入SDK核心类
const app = getApp();
import { requestApi } from '../../../api'
import { constants } from '../../../sdk/constants.js'
import { Uuid } from '../../../sdk/uuid.js'
import { extend } from '../../../sdk/extend'
import { formatImage } from '../../../utils/formatImage'
import { formatPrice, priceFormatNum } from '../../../utils/util'
import { dateFormat } from '../../../utils/dateFormat'
import { logUpload } from '../../../utils/logUpload'
import { colorSelect, specSelect } from '../../../templates/goodsSku/goodsSku'

Page({
  data: {
    gid: '',
    hiddenPage: true,
    uid: '',  // 登录用于UID
    scene: '',
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    Custom: app.globalData.Custom,
    channel: '',
    loading: false,               // loading
    swiperConfig: {
      indicatorDots: true,
      autoplay: true,
      interval: 3000,
      duration: 500,
      circular: true,
    },
    source_channel: ['国内现货', '海外现货', '代购', '现货', '预售'],
    goodsData: [],
    supportLaunchApp: app.data.supportLaunchApp,
    winWidth: wx.getSystemInfoSync().windowWidth,
    winHeight: wx.getSystemInfoSync().windowHeight,
    topicsType: '',           // 商品所在合集类型
    groupBuyingInfo: '',      // 拼团相关信息
    skuHidden: true,
    payFlag: false,           // 亲密购价格购买标识  true单独购买||false亲密购购买
    skuId: '',
    skuPrice: '',
    skuOriginPrice: '',
    skuTag: '',
    colorStyle: 0,
    specStyle: 0,
    uploadSpec: '',
    uploadColor: '',
    skuSpecVal: '',
    skuImage: '',
    showGuaranteeModal: true,
    showTaxModal: true,
    showPropertyModal: true,
    recom_start: 0,
    recom_title: '',
    recom_lists: [],
    isMoreEnd: false, // 加载更多
    timer: null,
  },
  onLoad: function (options) {
    let utm_info = {};
    let scene = '';
    let paramArr = [];
    let { gid, channel } = this.data;
    if (options.seller_uid) {
      // 商家端分享过来的
      wx.setStorageSync('seller_uid', options.seller_uid)
    }
    if (options.scene && options.scene.length) {
      // 二维码或者app分享
      scene = decodeURIComponent(options.scene)
      paramArr = scene.split(',')

      if (paramArr[1] == 'sl') {
        app.shortUrlToLong(paramArr[0], (res) => {
          gid = res.gid || '';
          channel = res.channel || '';
          utm_info = {
            utm_source: res.utm_source || '',
            utm_share: res.utm_share || '',
            utm_medium: res.utm_medium || '',
            utm_term: res.utm_term || '',
            utm_content: res.utm_content || '',
            utm_campaign: res.utm_campaign || '',
            utm_search_keyword: res.utm_search_keyword || '',
            utm_traffic_source_type: res.utm_traffic_source_type || ''
          }
        })
      } else {
        gid = paramArr[0];
        channel = paramArr[1];
      }
    } else {
      gid = options.gid || '';
      channel = options.channel || 'wx_xcx';
      utm_info = {
        utm_source: options.utm_source || '',
        utm_share: options.utm_share || '',
        utm_medium: options.utm_medium || '',
        utm_term: options.utm_term || '',
        utm_content: options.utm_content || '',
        utm_campaign: options.utm_campaign || '',
        utm_search_keyword: options.utm_search_keyword || '',
        utm_traffic_source_type: options.utm_traffic_source_type || ''
      }
    }

    this.setData({
      gid: gid,
      channel: channel,
      supportLaunchApp: app.data.supportLaunchApp,
      activeStatus: options.activeStatus || '',
      goodsUrl: 'ofashion://native/goodsDetail?gid=' + gid + '&utm_source=' + utm_info.utm_source + '&utm_share=' + utm_info.utm_share + '&utm_medium=' + utm_info.utm_medium + '&utm_term=' + utm_info.utm_term + '&utm_content=' + utm_info.utm_content + '&utm_campaign=' + utm_info.utm_campaign + '&utm_search_keyword=' + utm_info.utm_search_keyword + '&utm_traffic_source_type=' + utm_info.utm_traffic_source_type,
    });
    if (utm_info.utm_share) {
      // 分享场景
      this.shareInfoCommit(utm_info.utm_share);
    }

    this.shareUpload(utm_info);

    // 埋点上报
    let uploadParam = {
      cur_page_id: 'OFGoodsDetailViewController',
      cur_page_entrance_time: dateFormat('yyyy-MM-dd hh:mm:ss:S'),
      cur_page_entrance_type: 1,
      cur_page_resource_id: gid,
      opt_resource_area: 21,
      opt_resource_type: options.opt_resource_type || null,
      opt_resource_id: options.opt_resource_id || null,
      opt_resource_area_index: options.opt_resource_area_index || null,
      ref_page_id: options.ref_page_id || null,
      ref_page_resource_id: options.ref_page_resource_id || null,
      ref_opt_resource_id: options.ref_opt_resource_id || null,
      ref_opt_resource_type: options.ref_opt_resource_type || null,
      ref_opt_protocol: options.ref_opt_protocol || null,
      ref_write_sever_timestamp: options.ref_write_sever_timestamp || null,
      log_type: options.log_type || null,
    }

    logUpload.handleUpload(uploadParam)
  },
  onReady: function () {
    this.wechatDialog = this.selectComponent("#wechatDialog");
    this.doneDialog = this.selectComponent('#doneDialog')
  },
  onShow: function () {
    const { scene } = wx.getLaunchOptionsSync();
    const { gid, channel } = this.data;
    console.log(scene);
    this.setData({
      scene
    });

    if (scene == 1047 && !app.toLogin()) {
      this.setData({
        loading: true
      })
      return false
    } else {
      this.getGoodsData(gid, channel)
    }
  },
  getGoodsData(gid, channel) {
    app.request({
      url: requestApi.goodsDetail,
      login: false,
      data: {
        gid: gid,
        channel: channel,
        is_new_ver: true
      },
    }, (data) => {
      let goodsInfo, goodsData, priceInterval, shareTitle, shareDetail, shareImage, skuPrice, topicsType = '', groupBuyingInfo = '', remainTime = '', priceRef = '', remainTip, interval, smallGroupInfo, skuTag;

      goodsInfo = data.original.data.goods_info;
      // Gucci活动结束处理：自动跳转到首页
      if (goodsInfo.is_brand_activity == 1) {
        wx.switchTab({
          url: '../../index/index?channel=' + channel,
        })
        return true
      };


      goodsData = this.formatData(goodsInfo);
      shareTitle = goodsInfo.share_title;
      shareDetail = goodsInfo.share_detail;
      shareImage = goodsInfo.share_image;
      topicsType = goodsInfo.topics_type || '';

      goodsData.goods_color_list = goodsData.goods_color_list && goodsData.goods_color_list.filter(item => item.name != '') || [];
      goodsData.goods_size_list = goodsData.goods_size_list && goodsData.goods_size_list.filter(item => item.name != '') || [];

      if (goodsData.new_price_ref) {
        priceRef = goodsData.new_price_ref
      }

      if (goodsData.platform_activity_info) {
        skuTag = goodsData.platform_activity_info.activity_tag;
      }

      if (goodsData.wechat_number) {
        this.setData({
          wechat_number: goodsData.wechat_number
        })
      }

      if (goodsInfo.seller_info.seller_uid) {
        this.setData({
          seller_uid: goodsInfo.seller_info.seller_uid
        })
        app.getOpenId().then(async (res) => {
          let openid = res;
          // 更新关联关系
          app.addUseBbehavior(openid, goodsInfo.seller_info.seller_uid);
        }).catch(err => {
          console.log(err)
        })
      }
      // 亲密购倒计时
      if (goodsData.sales_promotion_type == 3) {
        if (goodsData.intimate_remain_time) {
          remainTime = goodsData.intimate_remain_time

          interval = setInterval(() => {
            remainTip = this.getRemainTime(remainTime)
            remainTime = remainTime - 1
            this.setData({
              remainTip: remainTip,
            })

            if (remainTime < 0) {
              clearInterval(interval)
            }
          }, 1000)
        }

        // 此商品正在进行的亲密购倒计时
        if (goodsData.small_group_info && goodsData.small_group_info.data_list && goodsData.small_group_info.data_list.length) {
          smallGroupInfo = goodsData.small_group_info.data_list

          for (let i = 0, len = smallGroupInfo.length; i < len; i++) {
            if (smallGroupInfo[i].remain_time) {
              let remainTimeName = 'remainTime' + i
              let intervalName = 'interval' + i

              remainTimeName = smallGroupInfo[i].remain_time
              intervalName = setInterval(() => {
                remainTip = this.getRemainTime(remainTimeName)
                remainTimeName = remainTimeName - 1
                smallGroupInfo[i].remain_tip = remainTip
                this.setData({
                  smallGroupInfo: smallGroupInfo,
                })

                if (remainTimeName < 0) {
                  clearInterval(intervalName)
                }
              }, 1000)
            }
          }
        }
      }

      // 拼团合集倒计时
      if (topicsType == 16) {
        if (goodsData.group_buying_info) {
          groupBuyingInfo = goodsData.group_buying_info || ''
          remainTime = goodsData.group_buying_info.remain_time

          interval = setInterval(() => {
            remainTip = this.getRemainTime(remainTime)
            remainTime = remainTime - 1
            this.setData({
              remainTip: remainTip,
            })

            if (remainTime < 0) {
              clearInterval(interval)
            }
          }, 1000)
        }
        priceRef = goodsData.new_original_price
      }

      // 限时活动倒计时
      if (topicsType == 15) {
        if (goodsData.remain_time) {
          remainTime = goodsData.remain_time

          interval = setInterval(() => {
            remainTip = this.getRemainTime(remainTime)
            remainTime = remainTime - 1
            this.setData({
              remainTip: remainTip,
            })

            if (remainTime < 0) {
              clearInterval(interval)
            }
          }, 1000)
        }
        priceRef = goodsData.new_original_price
      }

      // 分割换行：商品描述、交易备注
      goodsData.goods_description = goodsData.goods_description.split('\n').join('\r\n');
      goodsData.deal_comment = goodsData.deal_comment.split('\n').join('\r\n');

      if (goodsData.deal_comment.trim() === '') {
        goodsData.deal_comment = ''
      }

      if (goodsData.min_price == goodsData.max_price) {
        priceInterval = true
        skuPrice = goodsData.new_goods_price
      } else {
        priceInterval = false
        skuPrice = goodsData.new_min_price + ' - ' + goodsData.new_max_price
      }

      // sku选择唯一时默认选中
      if (goodsData.goods_color_list && goodsData.goods_color_list.length == 1 && goodsData.goods_size_list && goodsData.goods_size_list.length == 1) {
        for (let i = 0; i < goodsData.goods_sku.length; i++) {
          if (goodsData.goods_sku[i].goods_color_id == goodsData.goods_color_list[0].color_id && goodsData.goods_sku[i].goods_size_id == goodsData.goods_size_list[0].size_id) {
            const obj = {
              skuId: goodsData.goods_sku[i].sku_id,
              skuSpecVal: goodsData.goods_sku[i].goods_spec,
              colorStyle: goodsData.goods_color_list[0].color_id,
              specStyle: goodsData.goods_size_list[0].size_id,
            };

            if (goodsData.platform_activity_info && goodsData.platform_activity_info.isStart) {
              const info = goodsData.platform_activity_sku_list.find(item => item.sku_id == goodsData.goods_sku[i].sku_id);

              obj['skuOriginPrice'] = formatPrice(info.market_price / 100);
            }
            this.setData(obj);
          }
        }
      }

      // 给通过小程序二维码扫码进入的快闪店用户，添加标识
      const { scene } = this.data;
      if (scene == 1047) {
        this.setUserFlashName(goodsData.seller_uid, goodsData.shop_tag);
      }

      this.setData({
        goodsData: goodsData,
        isFavorite: goodsData.is_favorite || '',
        shareTitle: shareTitle,
        shareDetail: shareDetail,
        shareImage: shareImage,
        priceInterval: priceInterval,
        skuImage: goodsData.product_cover_image.new_path,
        skuTag: skuTag,
        skuPrice: skuPrice,
        loading: true,
        favoriteHidden: false,
        topicsType: topicsType,
        groupBuyingInfo: groupBuyingInfo,
        remainTime: remainTime,
        priceRef: priceRef,
        is_reservation_goods: goodsInfo.is_reservation_goods,
        shareCampaign: goodsData.utm_campaign || '',
        hiddenPage: false,
      })

      // 活动的开始后，倒计时
      this.activityEndTime();
    }, (error) => {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: error,
      })
    }, () => {
      const { recom_start } = this.data;
      this.getRecomGoods(recom_start);
    })
  },
  // 授权品牌
  goAccredit() {
    const { goodsData, channel } = this.data;

    wx.navigateTo({
      url: '/pages/categoryHall/categoryHall?keywords=' + goodsData.product_brandname_c + '&channel=' + channel,
    })
  },

  stopScroll() { },
  // 搜索标签
  goSearchTag(e) {
    const { channel } = this.data;
    const { name } = e.currentTarget.dataset;

    wx.navigateTo({
      url: '/pages/categoryHall/categoryHall?keywords=' + name + '&channel=' + channel,
    })
  },
  // 跳转商品参数
  checkGoodsParam: function (e) {
    const { goodsData, showPropertyModal } = this.data;

    if (!goodsData.goods_property || !goodsData.goods_property.length) return false

    this.setData({
      showPropertyModal: !showPropertyModal
    })
  },
  previewImg(e) {
    const { id } = e.currentTarget;
    const { goodsData } = this.data;
    const arr = [];

    goodsData.bannerImgs.every(item => arr.push(item.new_path));
    wx.previewImage({
      current: arr[id], // 当前显示图片的http链接
      urls: arr // 需要预览的图片http链接列表
    })
  },
  // 优惠券
  toCouponList: function () {
    let gid = this.data.gid

    wx.navigateTo({
      url: '../coupon/coupon?gid=' + gid,
    })
  },

  backPage() {
    console.log(getCurrentPages().length)
    if (getCurrentPages().length > 1) {
      wx.navigateBack()
    } else {
      console.log(11111)
      if (this.data.seller_uid) {
        // 有店铺
        wx.reLaunch({
          url: '/pages/store/store?seller_uid=' + this.data.seller_uid
        })
      } else {
        console.log(222)
        wx.switchTab({
          url: '/pages/index/index',
        })
      }

    }

  },
  // 购买弹窗
  toggleSku(e) {
    let { goodsData, skuHidden } = this.data;
    let payFlag = e.currentTarget.dataset.flag || false
    let skuPrice

    if (!app.toLogin()) {
      this.setData({
        loading: true
      })

      return false
    }

    // 海外商品不显示颜色规格
    if (goodsData.is_overseas_goods == 1) {
      return false;
    }

    if (payFlag) {
      //亲密购商品单独买价格
      skuPrice = goodsData.new_original_price
    } else {
      // 是否是活动且活动库存不为0
      if (goodsData.platform_activity_info && goodsData.platform_activity_info.isStart && goodsData.platform_activity_info.activity_stock) {
        if (goodsData.max_available_coupon) {
          skuPrice = goodsData.min_price != goodsData.max_price ? formatPrice(goodsData.min_price / 100) + ' ~ ' + formatPrice(goodsData.max_price / 100) : formatPrice((goodsData.min_price - goodsData.max_available_coupon.amount) / 100);
        } else {
          skuPrice = goodsData.min_price != goodsData.max_price ? formatPrice(goodsData.min_price / 100) + ' ~ ' + formatPrice(goodsData.max_price / 100) : formatPrice(goodsData.min_price / 100);
        }
      } else {
        if (goodsData.max_available_coupon) {
          skuPrice = formatPrice((goodsData.goods_price - goodsData.max_available_coupon.amount) / 100);
        } else {
          if (goodsData.max_available_coupon) {
            skuPrice = formatPrice((goodsData.goods_price - goodsData.max_available_coupon.amount) / 100);
          } else {
            skuPrice = formatPrice(goodsData.goods_price / 100);
          }
        }
      }
    }

    // 兼容错误数据（颜色list或款式list缺失）
    if (!goodsData.goods_color_list || !goodsData.goods_size_list) {
      wx.showToast({
        title: '商品信息有误，请联系客服～',
        icon: 'none',
        duration: 2000
      })

      return false
    }

    // 清除颜色规格的disabled
    for (let i = 0, len = goodsData.goods_color_list.length; i < len; i++) {
      goodsData.goods_color_list[i].noStock = false
    }
    for (let i = 0, len = goodsData.goods_size_list.length; i < len; i++) {
      const arr = goodsData.goods_sku.filter(item => item.goods_size_id == goodsData.goods_size_list[i].size_id);

      if (arr.length) {
        goodsData.goods_size_list[i].noStock = false
      } else {
        goodsData.goods_size_list[i].noStock = true
      }
    }

    // 如果接口返回了最佳优惠券未领取，需要优先领取优惠券
    if (goodsData.max_available_coupon && goodsData.max_available_coupon.status == 3 && skuHidden) {
      app.request({
        url: requestApi.receiveStoreCouponUrl,
        data: {
          coupon_no: goodsData.max_available_coupon.coupon_no,
        }
      }, (data) => {
        if (data.original.ret_code == 200) {
          this.setData({
            ['goodsData.max_available_coupon.status']: 1
          })
        }
      }, (error) => {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: error,
        })
      })
    }

    this.setData({
      goodsData: goodsData,
      skuHidden: !skuHidden,
      payFlag: payFlag,
      skuPrice: skuPrice,
    })

    if (goodsData.goods_color_list.length > 1 || goodsData.goods_size_list.length > 1) {
      this.setData({
        colorStyle: 0,
        specStyle: 0,
      })
    }
  },
  // 确认订单
  toConfirmPage() {
    const self = this;
    const { skuId, gid, uploadColor, uploadSpec, goodsData, payFlag, skuPrice, skuSpecVal, skuImage, channel } = self.data;

    if (!skuId) return false;

    const sku_info = goodsData.goods_sku.find(item => item.sku_id == skuId);

    let uploadParam = {
      cur_page_id: 'OFOrderEditViewController',
      ref_page_id: 'OFPopGoodsSKUViewController',
      ref_page_resource_id: gid,
      goods_color: uploadColor,
      goods_spec: uploadSpec,
      gid: gid,
      log_type: 1,
    }

    logUpload.handleUpload(uploadParam)

    let activityType = goodsData.sales_promotion_type || ''   // 活动类型
    let url = '../goodsTrade/goodsTrade?sku_price=' + skuPrice + '&activity_type=' + activityType + '&sku_spec=' + skuSpecVal + '&sku_id=' + skuId + '&gid=' + gid + '&chanel=' + channel;
    if (activityType == 3 && payFlag) {
      // 亲密购商品 && 单独价格购买
      activityType = ''
    }

    if (sku_info) {
      url = `${url}&bid_seller_uid=${sku_info.bid_seller_uid}`;
    }

    url = url + '&sku_img=' + skuImage;

    wx.navigateTo({
      url: url,
      success(res) {
        if (goodsData.max_available_coupon) {
          res.eventChannel.emit('max_available_coupon', goodsData.max_available_coupon);
        }

        self.setData({
          skuHidden: true
        })
      }
    })

  },
  topPreSale() {
    const { skuHidden } = this.data;
    this.setData({
      skuHidden: !skuHidden,
    })
  },
  // 添加心愿单
  addToFavorite: function (isSHowPop = true) {
    if (!app.toLogin()) {
      this.setData({
        loading: true
      })

      return false
    }

    if (this.data.requestFlag) return false;
    const { isFavorite } = this.data;
    this.data.requestFlag = true;

    let operateType = isFavorite == 0 ? 1 : 0;

    if (!isSHowPop) {
      operateType = 1;
    }

    app.request({
      url: operateType === 1 ? requestApi.setFavoriteGoods : requestApi.cancelFavoriteGoods,
      method: 'POST',
      data: {
        operate_type: operateType,
        gid: this.data.gid,
      },
    }, (data) => {
      if (isSHowPop) {
        wx.showToast({
          title: '操作成功！',
          duration: 1000,
        })
      }

      this.setData({
        isFavorite: operateType
      })
    }, (error) => {
      if (isSHowPop) {
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: error,
        })
      }
    }, () => {
      this.data.requestFlag = false
    })
  },
  sellerTap: function (e) {
    let seller_uid = e.currentTarget.id

    this.isFlashStore(seller_uid);
  },
  isFlashStore: function (seller_uid) {
    app.request({
      url: requestApi.isFlashStore,
      login: false,
      data: {
        seller_uid: seller_uid
      },
    }, (data) => {
      if (data.original.data.is_flash) {
        wx.navigateTo({
          url: '/pages/shop/shop?shop_id=' + data.original.data.id + '&seller_uid=' + seller_uid,
        })
      } else {
        wx.navigateTo({
          url: '../../store/store?seller_uid=' + seller_uid,
        })
      }
    }, (error) => {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: error,
      })
    })
  },
  openApp() {
    if (app.toLogin()) {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '请前往应用下载或直接打开迷橙APP',
      });

      this.addToFavorite(false);
    }
  },
  setUserFlashName(id, shop_name) {
    app.request({
      url: requestApi.setUserFlashName,
      login: false,
      data: {
        login_uid: id,
        flash_shop_tag: shop_name
      },
    }, (data) => {
      let d = data.original;
      if (d.status == 'success') {

      }
    }, (error) => {
      // wx.showModal({
      //     title: '提示',
      //     showCancel: false,
      //     content: error,
      // })
    })
  },
  toggleColor(e) {
    let curSpecName = e.currentTarget.dataset.value
    let currId = e.currentTarget.id
    let payFlag = this.data.payFlag
    let currSpecId = this.data.skuSpecId
    let skuList = this.data.goodsData.goods_sku
    let sizeList = this.data.goodsData.goods_size_list
    let platform_activity_info = this.data.goodsData.platform_activity_info
    let max_available_coupon = this.data.goodsData.max_available_coupon;
    let result = colorSelect(currId, currSpecId, skuList, sizeList, payFlag, this.data.goodsData.platform_activity_sku_list)

    if (!result.skuImg) {
      result.skuImg = this.data.skuImage
    }

    if (!result.skuPrice) {
      result.skuPrice = this.data.skuPrice
    }

    if (platform_activity_info && platform_activity_info.isStart) {
      const activityInfo = this.data.goodsData.platform_activity_sku_list.find(item => item.sku_id == result.skuId);

      if (activityInfo && activityInfo.activity_stock > 0) {
        max_available_coupon = this.data.goodsData.max_available_coupon_platform;
        this.data.goodsData['max_available_coupon'] = extend({}, this.data.goodsData['max_available_coupon'], max_available_coupon);
      }
    } else {
      result.skuOriginPrice = '';
    }

    // 如果商品有可领取的优惠券
    if (max_available_coupon && result.skuId) {
      result.skuPrice = String(result.skuPrice).split(',').join('');
      result.skuPrice = formatPrice((result.skuPrice * 100 - max_available_coupon.amount) / 100);
    }

    this.setData({
      goodsData: this.data.goodsData,
      skuColorId: currId,
      colorStyle: currId,
      skuImage: result.skuImg,
      skuPrice: result.skuPrice,
      skuOriginPrice: result.skuOriginPrice,
      skuSpecVal: result.skuSpec,
      skuId: result.skuId,
      uploadSpec: curSpecName
    })
  },
  toggleSpec(e) {
    let curColorName = e.currentTarget.dataset.value
    let currId = e.currentTarget.id
    let payFlag = this.data.payFlag
    let currColorId = this.data.skuColorId
    let skuList = this.data.goodsData.goods_sku
    let colorList = this.data.goodsData.goods_color_list
    let platform_activity_info = this.data.goodsData.platform_activity_info
    let max_available_coupon = this.data.goodsData.max_available_coupon;
    let result = specSelect(currId, currColorId, skuList, colorList, payFlag, this.data.goodsData.platform_activity_sku_list)

    if (!result.skuImg) {
      result.skuImg = this.data.skuImage
    }

    if (!result.skuPrice) {
      result.skuPrice = this.data.skuPrice
    }

    if (platform_activity_info && platform_activity_info.isStart) {
      const activityInfo = this.data.goodsData.platform_activity_sku_list.find(item => item.sku_id == result.skuId);

      if (activityInfo && activityInfo.activity_stock > 0) {
        max_available_coupon = this.data.goodsData.max_available_coupon_platform;
        this.data.goodsData['max_available_coupon'] = extend({}, this.data.goodsData['max_available_coupon'], max_available_coupon);
      }
    } else {
      result.skuOriginPrice = '';
    }

    // 如果商品有可领取的优惠券
    if (max_available_coupon && result.skuId) {
      result.skuPrice = String(result.skuPrice).split(',').join('');
      result.skuPrice = formatPrice((result.skuPrice * 100 - max_available_coupon.amount) / 100);
    }


    this.setData({
      goodsData: this.data.goodsData,
      skuSpecId: currId,
      specStyle: currId,
      skuImage: result.skuImg,
      skuPrice: result.skuPrice,
      skuOriginPrice: result.skuOriginPrice,
      skuSpecVal: result.skuSpec,
      skuId: result.skuId,
      uploadColor: curColorName,
    })
  },
  // 倒计时功能
  getRemainTime: function (time) {
    if (time < 0) return false

    let differTimestamp = time
    let deltaHour = Math.floor(differTimestamp / (60 * 60))
    let deltaMinute = Math.floor((differTimestamp % (60 * 60)) / 60)
    let deltaSecond = Math.floor(differTimestamp % 60)
    deltaHour = deltaHour < 10 ? ('0' + deltaHour) : deltaHour
    deltaMinute = deltaMinute < 10 ? ('0' + deltaMinute) : deltaMinute
    deltaSecond = deltaSecond < 10 ? ('0' + deltaSecond) : deltaSecond
    let deltaDate = deltaHour + ':' + deltaMinute + ':' + deltaSecond

    return deltaDate
  },
  // 处理请求返回的数据
  formatData: function (data) {
    let bannerImgs = []   // 轮播图片

    if (data.goods_auth_uri) {
      data.new_goods_auth_uri = formatImage.cdnImage(data.goods_auth_uri, formatImage.THUMBNAIL_M)
    }

    // 判断是否是海外商品
    if (String('2,3').indexOf(data.goods_channel_source) >= 0 && String('2,4,7,8').indexOf(data.seller_info.seller_type) >= 0) {
      data.is_overseas_goods = 1
    } else {
      data.is_overseas_goods = 0
    }

    if (data.quality_guarantee_info && data.quality_guarantee_info.item_list) {
      data.quality_guarantee_info.item_list.forEach(item => item.full_path = formatImage.cdnImage(item.url, formatImage.THUMBNAIL_S))
    }

    if (data.global_icon && data.global_icon.path) {
      data.global_icon.new_path = formatImage.cdnImage(data.global_icon.path, formatImage.THUMBNAIL_S)
    }

    if (data.goods_status_icon && data.goods_status_icon.path) {
      data.goods_status_icon.new_path = formatImage.cdnImage(data.goods_status_icon.path, formatImage.THUMBNAIL_S)
    }

    if (data.product_cover_image && data.product_cover_image.path) {
      data.product_cover_image.new_path = formatImage.cdnImage(data.product_cover_image.path, formatImage.THUMBNAIL_M)
      bannerImgs.push(data.product_cover_image)
    }

    if (data.icon_image_list && data.icon_image_list.wechat_goods_detail_rules_first) {
      data.icon_image_list.wechat_goods_detail_rules_first.new_path = formatImage.cdnImage(data.icon_image_list.wechat_goods_detail_rules_first.path, formatImage.THUMBNAIL_XS)
    }

    if (data.icon_image_list && data.icon_image_list.wechat_goods_detail_rules_second) {
      data.icon_image_list.wechat_goods_detail_rules_second.new_path = formatImage.cdnImage(data.icon_image_list.wechat_goods_detail_rules_second.path, formatImage.THUMBNAIL_XS)
    }

    if (data.icon_image_list && data.icon_image_list.wechat_goods_detail_rules_third) {
      data.icon_image_list.wechat_goods_detail_rules_third.new_path = formatImage.cdnImage(data.icon_image_list.wechat_goods_detail_rules_third.path, formatImage.THUMBNAIL_XS)
    }

    data.new_goods_price = data.goods_price ? formatPrice(data.goods_price / 100) : ''
    data.shipping_info.new_shipping_rate = data.shipping_info.shipping_rate ? formatPrice(data.shipping_info.shipping_rate / 100) : '0'
    data.shipping_info.new_customs_duties = data.shipping_info.customs_duties ? formatPrice(data.shipping_info.customs_duties / 100) : '0'
    data.new_min_price = data.min_price ? formatPrice(data.min_price / 100) : ''
    data.new_max_price = data.max_price ? formatPrice(data.max_price / 100) : ''
    data.new_price_ref = data.price_ref ? formatPrice(data.price_ref / 100) : ''
    data.new_original_max_price = data.original_max_price ? formatPrice(data.original_max_price / 100) : ''
    data.new_original_min_price = data.original_min_price ? formatPrice(data.original_min_price / 100) : ''
    data.new_original_price = data.original_price ? formatPrice(data.original_price / 100) : ''

    data.goods_channel_source_c = data.goods_channel_source == 1 && data.is_mf_shop == 1 ? '极速发' : this.data.source_channel[data.goods_channel_source - 1];

    // 预售最低~最高价格
    if (data.pre_sale_activity) {
      data.pre_sale_activity.min_pre_price = data.pre_sale_activity.pre_min_price ? formatPrice(data.pre_sale_activity.pre_min_price / 100) : '';
      data.pre_sale_activity.max_pre_price = data.pre_sale_activity.pre_max_price ? formatPrice(data.pre_sale_activity.pre_max_price / 100) : '';

      let $d = new Date();
      let $begin = new Date(data.pre_sale_activity['info']['deposit_begin_time']);
      let $end = new Date(data.pre_sale_activity['info']['deposit_end_time']);

      if (data.pre_sale_activity.is_pre && ($d.getTime() > $end.getTime() || $d.getTime() < $begin.getTime())) {
        data.pre_sale_activity.is_pre = 0;
      }
    }

    // TODO 优化
    // 交付时间调整为仅展示发货时效 1天展示24小时，2天展示48下时，超过2天展示实际天数
    if (Number(data.shipping_info.estimate_time_all) == 1) {
      data.shipping_info.estimate_time_all_cn = '24小时'
    } else if (Number(data.shipping_info.estimate_time_all) == 2) {
      data.shipping_info.estimate_time_all_cn = '48小时'
    } else {
      data.shipping_info.estimate_time_all_cn = data.shipping_info.estimate_time_all + '天'
    }

    if (Number(data.shipping_info.estimate_time_delivery) == 1) {
      data.shipping_info.estimate_time_delivery_cn = '24小时'
    } else if (Number(data.shipping_info.estimate_time_delivery) == 2) {
      data.shipping_info.estimate_time_delivery_cn = '48小时'
    } else {
      data.shipping_info.estimate_time_delivery_cn = data.shipping_info.estimate_time_delivery + '天'
    }

    if (Number(data.shipping_info.estimate_time_arrival) == 1) {
      data.shipping_info.estimate_time_arrival_cn = '24小时'
    } else if (Number(data.shipping_info.estimate_time_arrival) == 2) {
      data.shipping_info.estimate_time_arrival_cn = '48小时'
    } else {
      data.shipping_info.estimate_time_arrival_cn = data.shipping_info.estimate_time_arrival + '天'
    }

    if (data.seller_info && data.seller_info.avatar_image_uri) {
      data.seller_info.new_avatar_image_uri = formatImage.cdnImage(data.seller_info.avatar_image_uri, formatImage.THUMBNAIL_S)
    }

    if (data.product_image_list) {
      for (let i = 0, len = data.product_image_list.length; i < len; i++) {
        if (data.product_image_list[i].path) {
          data.product_image_list[i].new_path = formatImage.cdnImage(data.product_image_list[i].path, formatImage.THUMBNAIL_M)
          bannerImgs.push(data.product_image_list[i])
        }
      }

      data.bannerImgs = bannerImgs
      data.product_image_list = bannerImgs

      // Gucci活动商品详情页只取3张图
      /*if (data.product_image_list.length > 3) {
          data.product_image_list = data.product_image_list.slice(0, 3)
      }*/
    }

    if (data.goods_sku) {
      for (let i = 0, len = data.goods_sku.length; i < len; i++) {
        if (data.goods_sku[i].image_list[0].path) {
          data.goods_sku[i].image_list[0].new_path = formatImage.cdnImage(data.goods_sku[i].image_list[0].path, formatImage.THUMBNAIL_S)
        }

        data.goods_sku[i].new_goods_price = data.goods_sku[i].goods_price ? (data.goods_sku[i].goods_price / 100) : ''
        data.goods_sku[i].goods_single_price_calculate = data.goods_sku[i].original_price ? (data.goods_sku[i].original_price / 100) : 0
        data.goods_sku[i].goods_price_calculate = data.goods_sku[i].goods_price ? (data.goods_sku[i].goods_price / 100) : 0

      }
    }

    data.share_title = data.product_brandname_e ? '来自OFashion迷橙的' + data.product_brandname_e : ''
    data.share_detail = data.product_name ? data.product_name : ''
    data.share_image = data.product_cover_image.new_path

    if (data.goods_guarantee) {
      for (let i = 0, len = data.goods_guarantee.length; i < len; i++) {
        data.goods_guarantee[i].new_url = formatImage.cdnImage(data.goods_guarantee[i].url, formatImage.THUMBNAIL_XS)
      }
    }

    // 亲密购详情图片
    if (data.small_group_info && data.small_group_info.data_list.length) {
      for (let i = 0, len = data.small_group_info.data_list.length; i < len; i++) {
        data.small_group_info.data_list[i].new_avatar_image_uri = formatImage.cdnImage(data.small_group_info.data_list[i].avatar_image_uri, formatImage.THUMBNAIL_XS)
      }
    }

    if (data.logistics_info && data.logistics_info.logistics_detail && data.logistics_info.logistics_detail.length) {
      data.logistics_info.logistics_detail.forEach(item => {
        if (item.title == '预估税费') {
          data.tax_params = item
        }
      })
    }

    if (data.activity_is_begin) {
      // data.platform_activity_info = {
      //     "id": data.activity_id,
      // 	"activity_name": data.activity_name,
      // 	"begin_time": data.activity_begin_time,
      // 	"end_time": data.activity_end_time,
      // 	"status": data.activity_is_begin,
      // 	"activity_tag": data.activity_tag,
      // 	"activity_goods_stock_nil_desc": data.activity_goods_stock_nil_desc,
      // 	"activity_shop_end_time": data.activity_shop_end_time
      // }
    }

    // 活动相关数据处理
    if (data.platform_activity_info) {
      data.platform_activity_info.isStart = new Date(data.platform_activity_info.begin_time.replace(/\.|\-/g, '/')) < new Date()
      data.platform_activity_info.begin_time_show = dateFormat('MM-dd hh:mm', data.platform_activity_info.begin_time)

      let stock = 0;
      data.platform_activity_sku_list.map(item => stock += item.activity_stock * 1);
      data.platform_activity_info.activity_stock = stock;

      if (!stock) {
        data.platform_activity_info.status = 4;
      }
      // 活动开始后价格处理
      if (data.platform_activity_info.isStart) {
        data.platform_activity_info.min_activity_price = Math.min.apply(Math, data.platform_activity_sku_list.map(function (o) { return Number(o.activity_price) }))
        data.platform_activity_info.min_activity_price = formatPrice(data.platform_activity_info.min_activity_price / 100)
        data.platform_activity_info.max_activity_price = Math.max.apply(Math, data.platform_activity_sku_list.map(function (o) { return Number(o.activity_price) }))
        data.platform_activity_info.max_activity_price = formatPrice(data.platform_activity_info.max_activity_price / 100)

        // 活动中，库存卖光，显示原价
        let list = data.platform_activity_sku_list, t = 1;
        if (!data.platform_activity_info.activity_stock) {
          list = data.goods_sku;
          t = 0
        }

        data.platform_activity_info.min_market_price = Math.min.apply(Math, list.map(function (o) { return t ? Number(o.market_price) : Number(o.goods_price) }))
        data.platform_activity_info.min_market_price = formatPrice(data.platform_activity_info.min_market_price / 100)
        data.platform_activity_info.max_market_price = Math.max.apply(Math, list.map(function (o) { return t ? Number(o.market_price) : Number(o.goods_price) }))
        data.platform_activity_info.max_market_price = formatPrice(data.platform_activity_info.max_market_price / 100)

        if (data.goods_sku) {
          for (let i = 0; i < data.platform_activity_sku_list.length; i++) {
            for (let j = 0; j < data.goods_sku.length; j++) {
              if (data.goods_sku[j].sku_id == data.platform_activity_sku_list[i].sku_id) {
                data.goods_sku[j].goods_price_calculate = data.platform_activity_sku_list[i].activity_price ? formatPrice(data.platform_activity_sku_list[i].activity_price / 100) : ''
              }
            }
          }
        }
        // 活动没开始时锁库存
      } else {
        let stockObj = {}

        for (let i = 0; i < data.platform_activity_sku_list.length; i++) {
          data.goods_stock = data.goods_stock - Number(data.platform_activity_sku_list[i].activity_stock)
          stockObj[data.platform_activity_sku_list[i].sku_id] = Number(data.platform_activity_sku_list[i].activity_stock)
        }

        // sku库存移除活动库存(非代购商品)
        if (data.goods_sku && data.goods_channel_source && data.goods_channel_source !== 3) {
          for (let i = 0; i < data.goods_sku.length; i++) {
            data.goods_sku[i].goods_stock = data.goods_sku[i].goods_stock - stockObj[data.goods_sku[i].sku_id]
          }

          data.goods_sku = data.goods_sku.filter(item => item.goods_stock > 0)
        }
      }
    }

    // 当返回有商家/平台的优惠券，才开始计算用券价格
    data.max_use_coupon_seller = data.max_use_coupon_seller || {};
    data.max_use_coupon_platform = data.max_use_coupon_platform || {};

    if (data.max_use_coupon_seller.coupon_id || data.max_use_coupon_platform.coupon_id) {


      // 2023 11.23更新  商家优惠券平台优惠券可同时使用
      let max_available_coupon = {
        coupon_seller_amount: data.max_use_coupon_seller.amount || 0,
        coupon_platform_amount: data.max_use_coupon_platform.amount || 0,
        status: 1,
        seller_coupon_id: data.max_use_coupon_seller.coupon_id || '',
        seller_coupon_no: data.max_use_coupon_seller.coupon_no || '',
        platform_coupon_id: data.max_use_coupon_platform.coupon_id || '',
        platform_coupon_no: data.max_use_coupon_platform.coupon_no || '',
        amount: (data.max_use_coupon_seller.amount || 0) + (data.max_use_coupon_platform.amount || 0)
      }



      data['max_available_coupon'] = max_available_coupon;

      if (data.platform_activity_info) {
        data.platform_activity_sku_list.sort((a, b) => {
          let x = a.activity_price, y = b.activity_price;

          if (a.activity_stock == 0) {
            x = a.goods_price
          }

          if (b.activity_stock == 0) {
            y = b.goods_price
          }

          return x - y;
        });

        if (data.platform_activity_info.isStart) {
          const minPriceInfo = data.platform_activity_sku_list.find(item => data.goods_sku.some(i => i.sku_id == item.sku_id) ? item : '');

          if (minPriceInfo.activity_stock != 0) {
            data['max_available_coupon']['goods_price'] = formatPrice(minPriceInfo.activity_price / 100);
            if (data.max_available_coupon_platform) {
              data['max_available_coupon'] = data.max_available_coupon_platform;
              data['max_available_coupon']['goods_price'] = formatPrice((minPriceInfo.activity_price - data['max_available_coupon'].amount) / 100);
            }
          } else {
            data['max_available_coupon']['goods_price'] = formatPrice((minPriceInfo.goods_price - data['max_available_coupon'].amount) / 100);
          }
        } else {
          const priceInfo = data.platform_activity_sku_list.find(item => {
            const sku = data.goods_sku.find(i => i.sku_id == item.sku_id);

            return sku && item.activity_stock != 0
          });
          // if (priceInfo.activity_stock > 0) {
          //     data['max_available_coupon']['goods_price'] = formatPrice((priceInfo.activity_price - data['max_available_coupon'].amount) / 100); 
          // } else {

          // }

          if (priceInfo) {
            data['max_available_coupon']['goods_price'] = formatPrice((priceInfo.goods_price - data['max_available_coupon'].amount) / 100);
          } else {
            const info = data.platform_activity_sku_list.find(item => item.activity_stock > 0);
            data['max_available_coupon']['goods_price'] = formatPrice((info.activity_price - data['max_available_coupon'].amount) / 100);
          }
        }
      } else {
        const priceInfo = data.goods_sku.filter(item => item.goods_stock > 0);
        priceInfo.sort((a, b) => a.goods_price - b.goods_price);
        data['max_available_coupon']['goods_price'] = formatPrice((priceInfo[0].goods_price - data['max_available_coupon'].amount) / 100);
      }
    }

    // BC税费：(最低SKU商品价格+商家运费+迷橙运费-商家优惠券)* 类目税费
    // CC税费=（商品金额-平台/商家优惠券）*类目税费
    let tax = 0; // 税费 = (最低SKU商品价格+商家运费+迷橙运费-商家优惠券)* 类目税费

    if (data.delivery_mode == 2) {
      const GOODS_PRICE = priceFormatNum(data.new_goods_price) * 1;
      const MIN_GOODS_PRICE = priceFormatNum(data.new_min_price) * 1;
      const MAX_GOODS_PRICE = priceFormatNum(data.new_max_price) * 1;
      const SUM_RATE = data.shipping_rate ? data.shipping_rate * 1 : 0; // 商家运费与迷橙运费总和
      const SHIP_COUPON = 0;
      // const SHIP_COUPON = data['max_available_coupon_seller'] ? data['max_available_coupon_seller'].amount * 1 : 0;

      if (data.tax_type == 1) {
        tax = Math.ceil((GOODS_PRICE + SUM_RATE - SHIP_COUPON) * data.bc_tax_rate);
        data.new_goods_price = formatPrice(Math.ceil((GOODS_PRICE + tax) / 100));

        tax = Math.ceil((MIN_GOODS_PRICE + SUM_RATE - SHIP_COUPON) * data.bc_tax_rate);
        data.new_min_price = formatPrice(Math.ceil((MIN_GOODS_PRICE + tax) / 100));

        tax = Math.ceil((MAX_GOODS_PRICE + SUM_RATE - SHIP_COUPON) * data.bc_tax_rate);
        data.new_max_price = formatPrice(Math.ceil((MAX_GOODS_PRICE + tax) / 100));
      } else if (data.tax_type == 2) {
        tax = Math.ceil((GOODS_PRICE - SHIP_COUPON) * data.cc_tax_rate);
        data.new_goods_price = formatPrice(Math.ceil((GOODS_PRICE + tax) / 100));

        tax = Math.ceil((MIN_GOODS_PRICE - SHIP_COUPON) * data.cc_tax_rate);
        data.new_min_price = formatPrice(Math.ceil((MIN_GOODS_PRICE + tax) / 100));

        tax = Math.ceil((MAX_GOODS_PRICE - SHIP_COUPON) * data.cc_tax_rate);
        data.new_max_price = formatPrice(Math.ceil((MAX_GOODS_PRICE + tax) / 100));
      }
    }

    return data
  },
  // 展示预估税费
  showTax() {
    const { showTaxModal } = this.data;

    this.setData({
      showTaxModal: !showTaxModal
    })
  },
  // 展示安全签等
  showGuarantee() {
    const { goodsData, showGuaranteeModal } = this.data;

    if (!goodsData.goods_guarantee || !goodsData.goods_guarantee.length) return false

    this.setData({
      showGuaranteeModal: !showGuaranteeModal
    })
  },

  // 运营导购分享关系数据上报
  shareInfoCommit(share_uid) {
    wx.login({
      success: (res) => {
        app.request({
          url: requestApi.getKey,
          method: 'POST',
          login: false,
          data: {
            js_code: res.code
          },
        }, (data) => {

          if (data.original.ret_code == 200) {
            let openid = data.original.data.openid;
            app.request({
              url: requestApi.commitShare,
              method: 'GET',
              login: false,
              data: {
                share_uid: share_uid,
                gid: this.data.gid,
                is_new_ver: true,
                openid,
              },
            }, (data) => {
              //
            }, (error) => {
              console.log(error)
            })
          }
        }, (error) => {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: error,
          })
        })
      }
    })

  },

  // 分享埋点数据上报
  shareUpload: function (params) {
    app.request({
      url: requestApi.shareUploadLogUrl,
      method: 'POST',
      login: false,
      data: {
        utm_source: params.utm_source,
        utm_share: params.utm_share,
        utm_medium: params.utm_medium,
        utm_term: params.utm_term,
        utm_content: params.utm_content,
        utm_campaign: params.utm_campaign,
        utm_search_keyword: params.utm_search_keyword,
        utm_traffic_source_type: params.utm_traffic_source_type,
      },
    }, (data) => {
      //
    }, (error) => {
      console.log(error)
    })
  },
  onShareAppMessage() {
    let gid = this.data.gid
    let utm_share = ''
    let userInfo = wx.getStorageSync('userinfo');
    if (!userInfo.uid) {
      utm_share = constants.SOURCE + '_' + Uuid.get()
    } else {
      utm_share = constants.SOURCE + '_' + userInfo.uid
    }

    console.log('/pages/goods/goodsDetail/goodsDetail?gid=' + gid + '&channel=wx_xcx&utm_source=9_1&utm_share=' + utm_share + '&utm_medium=OFGoodsDetailViewController&utm_campaign=' + this.data.shareCampaign + '&utm_term=' + this.data.shareUtmTerm + '&utm_content=' + this.data.shareUtmContent + '&utm_search_keyword=' + this.data.shareUtmSearchKeyword + '&utm_traffic_source_type=' + this.data.shareUtmTrafficSourceType)
    return {
      title: this.gblen(this.data.goodsData.product_name, 40) + "￥" + (this.data.goodsData.goods_price / 100),
      desc: this.data.shareDetail,
      path: '/pages/goods/goodsDetail/goodsDetail?gid=' + gid + '&channel=wx_xcx&utm_source=9_1&utm_share=' + utm_share + '&utm_medium=OFGoodsDetailViewController&utm_campaign=' + this.data.shareCampaign + '&utm_term=' + this.data.shareUtmTerm + '&utm_content=' + this.data.shareUtmContent + '&utm_search_keyword=' + this.data.shareUtmSearchKeyword + '&utm_traffic_source_type=' + this.data.shareUtmTrafficSourceType,
      imageUrl: this.data.shareImage,
    }
  },
  gblen(str, max) {
    var reg = /[^\x00-\xff]/g;

    if (str.replace(reg, 'aa').length <= max) {
      return str
    }

    var m = Math.floor(max / 2);

    for (var i = m, j = str.length; i < j; i++) {
      if (str.substring(0, i).replace(reg, 'aa').length >= max) {
        return str.substring(0, i) + '...';
      }
    }

    return str;
  },
  _confirmKnow() {
    this.doneDialog.hideDialog()
  },
  copyWechat: function (e) {
    const that = this

    wx.setClipboardData({
      data: e.currentTarget.dataset.copy,
      success(res) {
        wx.hideToast()
        that.wechatDialog.showDialog()
      }
    })
  },
  launchAppError(e) {
    if (e.detail.errMsg) {
      wx.showModal({
        title: '提示',
        content: app.data.launchAppFailTips,
        success: function (res) {
        }
      })
    }
  },
  getRecomGoods(recom_start) {
    if (recom_start) {
      wx.showLoading({
        title: '加载中...',
      });
    }
    let { gid, recom_lists, isMoreEnd } = this.data;

    app.request({
      url: requestApi.recomGoods,
      data: {
        gid: gid,
        start: recom_start,
        count: 30,
        call_type: 4,
        is_new_ver: true
      },
    }, (d) => {
      if (d.original.ret_code == 200) {
        if (!recom_start) {
          recom_lists = d.original.recommend_goods
        } else {
          recom_lists = recom_lists.concat(d.original.recommend_goods);
        }

        if (recom_lists.length >= d.original.recommend_goods) {
          isMoreEnd = !isMoreEnd
        }

        this.setData({
          recom_title: d.original.goods_title,
          recom_lists,
          isMoreEnd
        });
      }
    }, (error) => {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: error,
      })
    }, () => {
      wx.hideLoading();
    })
  },
  onReachBottom: function () {
    const { recom_lists, isMoreEnd } = this.data;

    if (!isMoreEnd) {
      this.getRecomGoods(recom_lists.length);
    }
  },
  activityEndTime() {
    const self = this;
    let { goodsData, timer } = this.data;

    clearInterval(timer);
    if (goodsData.platform_activity_info && goodsData.platform_activity_info.isStart && goodsData.platform_activity_info.activity_stock) {
      let diff = 0, endTime = goodsData.platform_activity_info.end_time;

      timer = setInterval(() => {
        diff = new Date(endTime) - new Date();

        if (diff >= 0 && diff < 2 * 60 * 60 * 1000) {
          self.setData({
            ['goodsData.platform_activity_info.countdown']: this.formatTime(diff / 1000)
          })
        } else {
          clearInterval(timer);
        }
      }, 1000);
    }
  },
  formatTime(duration) {
    var d = Math.floor(duration / (24 * 60 * 60));
    var h = (Math.floor(duration % (24 * 60 * 60) / (60 * 60)) + '').padStart(2, '0');
    var m = (Math.floor(duration % (60 * 60) / 60) + '').padStart(2, '0');
    var s = (Math.floor(duration % 60) + '').padStart(2, '0');

    if (d) {
      d = String(d).padStart(2, '0');
      return `${d}天 ${h}:${m}:${s}`;
    } else {
      return `${h}:${m}:${s}`
    }
  },
  // 正品保障
  goService() {
    const { goodsData } = this.data;
    let url = (goodsData.quality_guarantee_info && goodsData.quality_guarantee_info.protocol) || (goodsData.official_inspection_info && goodsData.official_inspection_info.protocol);

    if (url) {
      url = decodeURIComponent(url).split('value=')[1];
      wx.navigateTo({
        url: `/pages/webView/webView?url=${url}&type=service`,
      })
    }
  },
  onUnload() {
    let { timer } = this.data;

    clearInterval(timer);
  },


  onShareTimeline() {
    return {
      title: this.data.goodsData.product_name,
      imageUrl: this.data.goodsData.bannerImgs[0].new_path
    }
  },
})